package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.CreditsOrderService;
import com.example.service.CreditsShopsService;
import com.example.service.GetCreditsService;
import com.example.service.UserService;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 积分商品兑换订单
 */
@RestController
@RequestMapping("creditsOrder")
public class CreditsOrderController {

    @Autowired
    private CreditsOrderService service;

    @Autowired
    private GetCreditsService getCredits;

    @Autowired
    private CreditsShopsService creditsShopsService;

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private CreditsOrderController creditsOrder;

    // 库存加锁 防止库存被超卖
    Lock lock = new ReentrantLock();

    /**
     * @param json
     * @description: 分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getPage")
    public Result getPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        List<Map<String, Object>> list = service.getList(jsonObject);
        int total = service.getCount(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param json
     * @description: 列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getList")
    public Result getList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        List<Map<String, Object>> list = service.getList(jsonObject);
        return ResultUtil.success(list);
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getById")
    public Result getById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getById(map));
    }

    /**
     * @param map
     * @description: 撤销订单
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("cancleOrder")
    public Result cancleOrder(@RequestBody Map<String, Object> map) throws Exception {
        // 当前方法加锁 防止多个接口同时调用
        lock.lock();
        try {
            // 1. 查询订单状态是否为1
            Map<String, Object> orderMap = new HashMap();
            orderMap.put("id", map.get("id"));
            Map<String, Object> orderData = service.getById(orderMap);
            Integer added = (Integer) orderData.get("added");
            if (added == 1) {
                creditsOrder.returnCreditsAndCc(map, orderData);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(-500, "当前状态无法撤销");
            }
        } catch (Exception e) {
            return ResultUtil.error(-500, "撤销失败");
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void returnCreditsAndCc(Map<String, Object> map, Map<String, Object> orderData) {
        // 获取用户信息
        Map<String, Object> userMap = new HashMap();
        userMap.put("id", orderData.get("userId"));
        Map<String, Object> userInfo = userService.getById(userMap);
        // 1. 撤销订单
        map.put("added", 6);
        service.update(map);
        // 2. 查询商品信息  更新商品库存
        // 2.1 查询商品信息
        Map<String, Object> shopdetails = new HashMap();
        shopdetails.put("id", orderData.get("shopId"));
        Map<String, Object> ShopDetails = creditsShopsService.getById(shopdetails);
        // 2.2 更新商品库存
        Integer surpusStock = (Integer) ShopDetails.get("surplusStock");
        Map<String, Object> shopkc = new HashMap();
        surpusStock = surpusStock + 1;
        shopkc.put("id", ShopDetails.get("id"));
        shopkc.put("surplusStock", surpusStock);
        creditsShopsService.update(shopkc);
        // 3. 返还积分
        // 3.1 查询用户积分
        Map<String, Object> getCit = new HashMap<>();
        getCit.put("id", userInfo.get("id"));
        Map<String, Object> userCredit = getCredits.getMyCredits(getCit);
        // 计算 剩余积分+返还积分
        BigDecimal totalCredit = new BigDecimal(Double.valueOf(userCredit.get("total").toString()));// 剩余积分
        BigDecimal returnCredit = new BigDecimal(orderData.get("shopCreditsPrice").toString()); // 退还积分金额
        BigDecimal tdMoney = totalCredit.add(returnCredit).setScale(2, BigDecimal.ROUND_HALF_UP);//加法四舍五入保留两位小数
        // 插入数据
        Map<String, Object> creditAdd = new HashMap();
        creditAdd.put("id", IDTool.getUUID32()); // 用户id
        creditAdd.put("userId", userInfo.get("id")); // 用户id
        creditAdd.put("userPhone", userInfo.get("name")); // 用户手机号
        creditAdd.put("userName", userInfo.get("nikeName")); // 用户手机号
        creditAdd.put("creditsShopName", orderData.get("shopName")); // 商品名
        creditAdd.put("creditsShopSn", orderData.get("orderSn")); // 商品编号
        creditAdd.put("getCredits", orderData.get("shopCreditsPrice")); // 消耗积分
        creditAdd.put("creditsShopOrderSn", orderData.get("orderSn")); // 订单编号
        creditAdd.put("accountCredits", tdMoney); // 账户剩余积分
        // 插入记录
        getCredits.saveRefund(creditAdd);
    }

    /**
     * @param map
     * @description: 修改
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("update")
    public Result update(@RequestBody Map<String, Object> map) {
        service.update(map);
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 删除
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("delete")
    public Result delete(@RequestBody Map<String, Object> map) {
        service.delete(map);
        return ResultUtil.success();
    }
}
